package com.atguigu.stgy.common.config;

//import org.springframework.context.annotation.Configuration;

import com.atguigu.stgy.common.converter.BaseTypeEnumConverterFactory;
import com.atguigu.stgy.common.interceptor.StgyAuthInterceptor;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

//@Configuration
public class StgyWebMvcConfiguere implements WebMvcConfigurer {
    @Resource
    StgyAuthInterceptor stgyAuthInterceptor;
    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        SimpleModule module = new SimpleModule();
        module.addSerializer(Long.class, ToStringSerializer.instance);
//        module.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(module);
        return objectMapper;
    }
    //注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(stgyAuthInterceptor)
                .addPathPatterns("/**") //要拦截的路径
                .excludePathPatterns("/admin/login/**",
                        "/app/login/**",
                        //将来会直接访问 swagger页面  不能拦截
                        "/webjars/**",
                        "/favicon.ico",
                        "/v3/api-docs/**",
                        "/doc.html"); //要放行的路径
    }

    //全局跨域配置
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") //配置哪些路径 的跨域
                .allowedHeaders("*") //允许携带的请求头
                .allowCredentials(true) //是否允许携带cookie
                .allowedMethods("*") //允许那些请求方式
                .allowedOriginPatterns("*"); //允许那些客户端服务器访问
    }

    @Resource
    BaseTypeEnumConverterFactory factory;
    //枚举转换器工厂
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(factory);
    }

}
